package com.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.dao.UsersDAO;
import com.model.Users;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

public class UsersAction implements ModelDriven<Users>,ServletRequestAware{

	private Users users;
	private HttpServletRequest request;
	UsersDAO usersDAO=new UsersDAO();
	public String login() {
		Users u=usersDAO.get(users.getUsername(), users.getPassword());
		if (u!=null) {
			ActionContext atx=ActionContext.getContext();
			Map<String,Object> session=atx.getSession();
			session.put("loginUser", users);
			return "success";
		} else {
			return "login";
		}
	}
	
	public String logout() {
		ActionContext atx=ActionContext.getContext();
		Map<String,Object> session=atx.getSession();
		session.remove("loginUser");
		return "success";
	}

	public String show(){
		List<Users> userslist = usersDAO.getAll();
		request.setAttribute("userslist", userslist);
		return "success";
	}
	public String add() {
		 new UsersDAO().insert(users);
		 return "show";
	}
	public String delete() {
		 new UsersDAO().delete(users.getId());
		 return "show";
	}
	public String edit() {
		users = new UsersDAO().get(users.getId());
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("user", users);
		return "update";
	}
	public String update() {
		new UsersDAO().update(users);
		return "show";
	}
	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	@Override
	public Users getModel() {
		users=new Users();
		return this.getUsers();
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request=arg0;
	}

}
